import React, { Component } from "react";

export default class ChatCom extends Component {
  //声明状态
  state = {
    msgs: ["a", "b", "c"],
  };

  //声明 send 方法
  send = () => {
    //获取 input 元素当前输入的值
    let v = this.input.value;
    //更新状态
    this.setState({
      msgs: [...this.state.msgs, v],
    });
  };

  render() {
    return (
      <div>
        <input type="text" ref={(el) => (this.input = el)} />
        <button onClick={this.send}>发送</button>
        <hr />
        <div ref={el => this.div = el} style={{ border: "solid 1px #789", width: 400, height: 300, overflowY: 'auto' }}>
          {/* 列表渲染 */}
          <ul>
            {this.state.msgs.map((item, index) => {
              return <li key={index}>{item}</li>;
            })}
          </ul>
        </div>
      </div>
    );
  }

  //组件更新完成
  componentDidUpdate(){
    //修改 div 元素的滚动距离
    // this.div.scrollTop = this.div.scrollHeight - this.div.clientHeight;// 200000
    this.div.scrollTop = this.div.scrollHeight;
  }
}
